<template>
  <el-dialog
    :visible.sync="dialogVisible"
    title="AI 数据分析"
    width="90%"
    top="5vh"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-container style="height: 75vh;">
      <!-- 左侧：AI 交互区 -->
      <el-main style="padding: 10px 20px; border-right: 1px solid #dcdfe6;">
        <div class="ai-chat-container">
          <div ref="messagesContainer" class="chat-messages">
            <div
              v-for="(message, index) in chatMessages"
              :key="index"
              :class="['message-item', message.role]"
            >
              <div class="message-content">
                <div class="message-text" v-html="formatMessage(message.content)" />
              </div>
            </div>
          </div>

          <!-- 预设问题卡片 -->
          <div v-if="chatMessages.length === 0" class="suggested-questions">
            <div class="questions-title">
              <i class="el-icon-question" /> 选择一个问题开始分析
            </div>
            <div class="questions-grid">
              <div
                v-for="(item, index) in suggestedQuestions"
                :key="index"
                class="question-card"
                :style="{ borderColor: item.color }"
                @click="askQuestion(item.question)"
              >
                <i :class="item.icon" :style="{ color: item.color }" />
                <div class="question-title">{{ item.title }}</div>
                <div class="question-text">{{ item.question }}</div>
              </div>
            </div>
          </div>

          <div class="chat-input-area">
            <el-input
              v-model="userInput"
              type="textarea"
              :rows="3"
              placeholder="或者输入您的自定义问题..."
              @keyup.enter.native="handleSend"
            />
            <div class="input-actions">
              <el-button
                type="primary"
                :loading="analyzing"
                :disabled="!userInput.trim()"
                style="background-color: #1EB7E6; border-color: #1EB7E6; color: white;"
                @click="handleSend"
              >
                <i class="el-icon-magic-stick" /> {{ analyzing ? '分析中...' : 'AI 分析' }}
              </el-button>
              <el-button
                v-if="chatMessages.length > 0"
                type="success"
                :disabled="analyzing"
                @click="handleSaveResult"
              >
                <i class="el-icon-check" /> 保存分析结果
              </el-button>
            </div>
          </div>
        </div>
      </el-main>

      <!-- 右侧：结构化数据展示区 -->
      <el-aside width="45%" style="padding: 10px 20px;">
        <el-tabs v-model="activeTab" type="border-card">
          <el-tab-pane :label="`核心关键词 (${analysisData.core_keywords.length})`" name="core">
            <el-table :data="analysisData.core_keywords" border size="small" max-height="500">
              <el-table-column label="关键词" width="360">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.keyword"
                    size="small"
                    placeholder="请输入关键词"
                  />
                </template>
              </el-table-column>
              <el-table-column label="搜索量" width="100">
                <template slot-scope="scope">
                  <el-input
                    v-model.number="scope.row.volume"
                    size="small"
                    type="number"
                    placeholder="搜索量"
                  />
                </template>
              </el-table-column>
              <el-table-column label="难度" width="80">
                <template slot-scope="scope">
                  <el-input
                    v-model.number="scope.row.difficulty"
                    size="small"
                    type="number"
                    placeholder="难度"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click="removeKeyword('core_keywords', scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 10px;">
              <el-input
                v-model="batchInputCore"
                type="textarea"
                :rows="3"
                placeholder="批量添加关键词，每行一个。格式：关键词,搜索量,难度（搜索量和难度可选）&#10;示例：&#10;running shoes,10000,45&#10;best shoes,5000,50&#10;或直接输入：&#10;running shoes&#10;best shoes"
                style="margin-bottom: 5px;"
              />
              <el-button type="primary" size="small" @click="handleBatchAdd('core_keywords')">批量添加</el-button>
              <el-button size="small" @click="showAddKeywordDialog('core_keywords')">单个添加</el-button>
            </div>
          </el-tab-pane>

          <el-tab-pane :label="`LSI 关键词 (${analysisData.lsi_keywords.length})`" name="lsi">
            <el-table :data="analysisData.lsi_keywords" border size="small" max-height="500">
              <el-table-column label="关键词" min-width="200">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.keyword"
                    size="small"
                    placeholder="请输入 LSI 关键词"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click="removeKeyword('lsi_keywords', scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 10px;">
              <el-input
                v-model="batchInputLSI"
                type="textarea"
                :rows="3"
                placeholder="批量添加 LSI 关键词，每行一个&#10;示例：&#10;running shoes women&#10;best running shoes&#10;marathon shoes"
                style="margin-bottom: 5px;"
              />
              <el-button type="primary" size="small" @click="handleBatchAdd('lsi_keywords')">批量添加</el-button>
              <el-button size="small" @click="showAddKeywordDialog('lsi_keywords')">单个添加</el-button>
            </div>
          </el-tab-pane>

          <el-tab-pane :label="`相关关键词 (${analysisData.related_keywords.length})`" name="related">
            <el-table :data="analysisData.related_keywords" border size="small" max-height="500">
              <el-table-column label="关键词" min-width="200">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.keyword"
                    size="small"
                    placeholder="请输入相关关键词"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click="removeKeyword('related_keywords', scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 10px;">
              <el-input
                v-model="batchInputRelated"
                type="textarea"
                :rows="3"
                placeholder="批量添加相关关键词，每行一个&#10;示例：&#10;sneakers&#10;athletic shoes&#10;sports shoes"
                style="margin-bottom: 5px;"
              />
              <el-button type="primary" size="small" @click="handleBatchAdd('related_keywords')">批量添加</el-button>
              <el-button size="small" @click="showAddKeywordDialog('related_keywords')">单个添加</el-button>
            </div>
          </el-tab-pane>

          <el-tab-pane label="动机判断" name="intent">
            <el-form label-width="120px" size="small">
              <el-form-item label="搜索动机">
                <el-input
                  v-model="analysisData.search_intent"
                  type="textarea"
                  :rows="3"
                  placeholder="用户搜索这些关键词的主要动机和意图..."
                />
              </el-form-item>
              <el-form-item label="内容需求类型">
                <el-input
                  v-model="analysisData.content_type"
                  type="textarea"
                  :rows="3"
                  placeholder="用户需要什么类型的内容（教程、评测、对比、指南等）..."
                />
              </el-form-item>
              <el-form-item label="核心价值">
                <el-input
                  v-model="analysisData.core_value"
                  type="textarea"
                  :rows="3"
                  placeholder="这个内容能为用户带来什么核心价值..."
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-aside>
    </el-container>

    <!-- 添加关键词对话框 -->
    <el-dialog
      :visible.sync="addKeywordDialogVisible"
      title="添加关键词"
      width="400px"
      append-to-body
    >
      <el-form label-width="80px">
        <el-form-item label="关键词">
          <el-input v-model="newKeyword.keyword" placeholder="请输入关键词" />
        </el-form-item>
        <el-form-item v-if="addKeywordType === 'core_keywords'" label="搜索量">
          <el-input-number v-model="newKeyword.volume" :min="0" placeholder="搜索量" />
        </el-form-item>
        <el-form-item v-if="addKeywordType === 'core_keywords'" label="难度">
          <el-input-number v-model="newKeyword.difficulty" :min="0" :max="100" placeholder="难度" />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addKeywordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddKeyword">确定</el-button>
      </span>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { fetchTopicAnalysis, saveTopicAnalysis } from '@/api/topicanalysis'
import { marked } from 'marked'
import { getToken } from '@/utils/auth'

export default {
  name: 'TopicAnalysis',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    topicData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      dialogVisible: false,
      activeTab: 'core',
      analyzing: false,
      userInput: '',
      chatMessages: [],
      analysisData: {
        core_keywords: [],
        lsi_keywords: [],
        related_keywords: [],
        search_intent: '',
        content_type: '',
        core_value: ''
      },
      addKeywordDialogVisible: false,
      addKeywordType: '',
      newKeyword: {
        keyword: '',
        volume: 0,
        difficulty: 0
      },
      // 批量输入
      batchInputCore: '',
      batchInputLSI: '',
      batchInputRelated: '',
      // 预设问题列表
      suggestedQuestions: [
        {
          icon: 'el-icon-search',
          title: '核心关键词分析',
          question: '这个话题的核心搜索关键词是什么？请给出3-5个核心关键词，并评估它们的搜索量和难度。',
          color: '#409EFF'
        },
        {
          icon: 'el-icon-connection',
          title: 'LSI 语义关键词',
          question: '请列出与这个话题相关的10-15个LSI（Latent Semantic Indexing）语义关联关键词。',
          color: '#67C23A'
        },
        {
          icon: 'el-icon-link',
          title: '相关关键词扩展',
          question: '用户搜索这个话题时，还会搜索哪些相关的关键词？请列出10-15个相关搜索词。',
          color: '#E6A23C'
        },
        {
          icon: 'el-icon-user',
          title: '搜索动机分析',
          question: '用户搜索这个关键词的主要动机和意图是什么？他们想要解决什么问题或获得什么信息？',
          color: '#F56C6C'
        },
        {
          icon: 'el-icon-document',
          title: '内容需求类型',
          question: '用户需要什么类型的内容？（如：教程、评测、对比、购买指南、问题解答等）',
          color: '#909399'
        },
        {
          icon: 'el-icon-star-off',
          title: '核心价值定位',
          question: '这个内容能为用户提供什么核心价值？如何帮助用户解决他们的问题？',
          color: '#1EB7E6'
        }
      ]
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val) {
        this.loadAnalysisData()
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
    }
  },
  computed: {
    headers() {
      return {
        'Authorization': getToken(),
        'PTOKEN': this.$store.getters.projectId,
        'Content-Type': 'application/json'
      }
    }
  },
  methods: {
    // 点击预设问题
    askQuestion(question) {
      this.userInput = question
      this.handleSend()
    },

    async loadAnalysisData() {
      try {
        const res = await fetchTopicAnalysis(this.topicData.id)
        if (res.success && res.data) {
          // 加载已存在的分析数据
          this.analysisData = {
            core_keywords: res.data.core_keywords || [],
            lsi_keywords: res.data.lsi_keywords || [],
            related_keywords: res.data.related_keywords || [],
            search_intent: res.data.search_intent || '',
            content_type: res.data.content_type || '',
            core_value: res.data.core_value || ''
          }

          // 如果有 AI 分析原始数据，显示在聊天记录中
          if (res.data.ai_analysis_raw) {
            this.chatMessages.push({
              role: 'assistant',
              content: res.data.ai_analysis_raw
            })
          }
        }
      } catch (error) {
        console.error('加载分析数据失败:', error)
      }
    },

    async handleSend() {
      if (!this.userInput.trim()) return

      const userMessage = this.userInput
      this.chatMessages.push({
        role: 'user',
        content: userMessage
      })
      this.userInput = ''
      this.analyzing = true

      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom()
      })

      try {
        // 添加一个占位符消息
        const assistantIndex = this.chatMessages.length
        this.chatMessages.push({
          role: 'assistant',
          content: ''
        })

        // 调用 AI 分析 API（流式）
        const response = await fetch(`${process.env.VUE_APP_BASE_API}/cms/api/topicanalysis_ai_analyze/`, {
          method: 'POST',
          headers: this.headers,
          body: JSON.stringify({
            topic_id: this.topicData.id,
            user_prompt: userMessage,
            engine: 'claude-sonnet-4.5'
          })
        })

        const reader = response.body.getReader()
        const decoder = new TextDecoder()
        let fullText = ''

        // eslint-disable-next-line no-constant-condition
        while (true) {
          const { done, value } = await reader.read()
          if (done) break

          const chunk = decoder.decode(value)
          fullText += chunk
          this.chatMessages[assistantIndex].content = fullText

          // 自动滚动到底部
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        }

        // 尝试解析 JSON 数据并填充到右侧面板
        this.parseAIResult(fullText)
      } catch (error) {
        this.$message.error('AI 分析失败: ' + error.message)
        console.error('AI 分析错误:', error)
      } finally {
        this.analyzing = false
      }
    },

    parseAIResult(text) {
      try {
        // 尝试从文本中提取 JSON
        const jsonMatch = text.match(/\{[\s\S]*\}/)
        if (jsonMatch) {
          const data = JSON.parse(jsonMatch[0])

          if (data.core_keywords) {
            this.analysisData.core_keywords = data.core_keywords
          }
          if (data.lsi_keywords) {
            this.analysisData.lsi_keywords = data.lsi_keywords
          }
          if (data.related_keywords) {
            this.analysisData.related_keywords = data.related_keywords
          }
          if (data.search_intent) {
            this.analysisData.search_intent = data.search_intent
          }
          if (data.content_type) {
            this.analysisData.content_type = data.content_type
          }
          if (data.core_value) {
            this.analysisData.core_value = data.core_value
          }

          this.$message.success('AI 分析结果已自动填充到右侧面板')
        }
      } catch (error) {
        console.log('无法自动解析 JSON，请手动编辑')
      }
    },

    async handleSaveResult() {
      try {
        // 获取完整的 AI 对话内容
        const aiResult = this.chatMessages
          .filter(m => m.role === 'assistant')
          .map(m => m.content)
          .join('\n\n---\n\n')

        const res = await saveTopicAnalysis({
          topic_id: this.topicData.id,
          ai_result: aiResult,
          parsed_data: this.analysisData
        })

        if (res.success) {
          this.$message.success('分析结果已保存')
          this.$emit('saved', res.data)
        } else {
          this.$message.error(res.msg || '保存失败')
        }
      } catch (error) {
        this.$message.error('保存失败: ' + error.message)
        console.error('保存错误:', error)
      }
    },

    showAddKeywordDialog(type) {
      this.addKeywordType = type
      this.newKeyword = {
        keyword: '',
        volume: 0,
        difficulty: 0
      }
      this.addKeywordDialogVisible = true
    },

    handleAddKeyword() {
      if (!this.newKeyword.keyword.trim()) {
        this.$message.warning('请输入关键词')
        return
      }

      if (this.addKeywordType === 'core_keywords') {
        this.analysisData.core_keywords.push({
          keyword: this.newKeyword.keyword,
          volume: this.newKeyword.volume,
          difficulty: this.newKeyword.difficulty
        })
      } else {
        this.analysisData[this.addKeywordType].push({
          keyword: this.newKeyword.keyword
        })
      }

      this.addKeywordDialogVisible = false
    },

    // 批量添加关键词
    handleBatchAdd(type) {
      let inputText = ''
      if (type === 'core_keywords') {
        inputText = this.batchInputCore
      } else if (type === 'lsi_keywords') {
        inputText = this.batchInputLSI
      } else if (type === 'related_keywords') {
        inputText = this.batchInputRelated
      }

      if (!inputText.trim()) {
        this.$message.warning('请输入关键词')
        return
      }

      const lines = inputText.split('\n').filter(line => line.trim())
      let addedCount = 0

      lines.forEach(line => {
        const trimmedLine = line.trim()
        if (!trimmedLine) return

        if (type === 'core_keywords') {
          // 支持 "关键词,搜索量,难度" 或只输入关键词
          const parts = trimmedLine.split(',').map(p => p.trim())
          const keyword = parts[0]
          const volume = parts[1] ? parseInt(parts[1]) || 0 : 0
          const difficulty = parts[2] ? parseInt(parts[2]) || 0 : 0

          if (keyword) {
            this.analysisData.core_keywords.push({
              keyword: keyword,
              volume: volume,
              difficulty: difficulty
            })
            addedCount++
          }
        } else {
          // LSI 和相关关键词，每行一个关键词
          this.analysisData[type].push({
            keyword: trimmedLine
          })
          addedCount++
        }
      })

      // 清空输入框
      if (type === 'core_keywords') {
        this.batchInputCore = ''
      } else if (type === 'lsi_keywords') {
        this.batchInputLSI = ''
      } else if (type === 'related_keywords') {
        this.batchInputRelated = ''
      }

      this.$message.success(`成功添加 ${addedCount} 个关键词`)
    },

    removeKeyword(type, index) {
      this.analysisData[type].splice(index, 1)
    },

    formatMessage(content) {
      if (!content) return ''
      return marked(content)
    },

    scrollToBottom() {
      const container = this.$refs.messagesContainer
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    },

    handleClose() {
      this.$emit('close')
    }
  }
}
</script>

<style scoped>
.ai-chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 15px;
}

.message-item {
  margin-bottom: 15px;
  display: flex;
}

.message-item.user {
  justify-content: flex-end;
}

.message-item.assistant {
  justify-content: flex-start;
}

.message-content {
  max-width: 80%;
  padding: 10px 15px;
  border-radius: 8px;
  word-wrap: break-word;
}

.message-item.user .message-content {
  background: #409EFF;
  color: white;
}

.message-item.assistant .message-content {
  background: white;
  color: #303133;
  border: 1px solid #e4e7ed;
}

.message-text {
  font-size: 14px;
  line-height: 1.6;
}

.chat-input-area {
  border-top: 1px solid #dcdfe6;
  padding-top: 15px;
}

.keywords-tag-container {
  min-height: 100px;
  max-height: 300px;
  overflow-y: auto;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

/* 预设问题样式 */
.suggested-questions {
  margin-bottom: 20px;
}

.questions-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.questions-title i {
  font-size: 18px;
  margin-right: 8px;
  color: #1EB7E6;
}

.questions-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.question-card {
  padding: 15px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
}

.question-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: currentColor;
}

.question-card i {
  font-size: 24px;
  margin-bottom: 8px;
  display: block;
}

.question-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 6px;
}

.question-text {
  font-size: 12px;
  color: #606266;
  line-height: 1.5;
}

.input-actions {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}
</style>
